package org.tloss.web.editor.editors.configuration;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;

import org.eclipse.jface.viewers.ITreeContentProvider;
import org.eclipse.jface.viewers.Viewer;

public class PropertyProvinder implements ITreeContentProvider {

	@Override
	public void dispose() {

	}

	@Override
	public void inputChanged(Viewer viewer, Object oldInput, Object newInput) {

	}

	@Override
	public Object[] getElements(Object inputElement) {
		return getChildren(inputElement);
	}

	@Override
	public Object[] getChildren(Object parentElement) {
		if (parentElement != null && parentElement instanceof Properties) {
			Set<Entry<Object, Object>> entries = ((Properties) parentElement)
					.entrySet();
			if (entries.size() > 0) {
				List<Object> config = new ArrayList<Object>();
				Iterator<Entry<Object, Object>> iterator = entries.iterator();
				Entry<Object, Object> entry;
				org.tloss.web.editor.editors.configuration.Entry e;
				while (iterator.hasNext()) {
					entry = iterator.next();
					e = new org.tloss.web.editor.editors.configuration.Entry();
					e.setKey(entry.getKey());
					e.setValue(entry.getValue());
					config.add(e);
				}
				/*Collections.sort(config, new Comparator<Object>() {
					@SuppressWarnings("rawtypes")
					@Override
					public int compare(Object o1, Object o2) {
						if (o1 != null
								&& o2 != null
								&& o1 instanceof org.tloss.web.editor.editors.configuration.Entry
								&& o2 instanceof org.tloss.web.editor.editors.configuration.Entry) {
							return ((org.tloss.web.editor.editors.configuration.Entry) o1)
									.getKey()
									.toString()
									.compareTo(
											((org.tloss.web.editor.editors.configuration.Entry) o2)
													.getKey().toString());
						}
						return 0;
					}
				});*/
				return config.toArray();
			}

		}
		return Collections.EMPTY_LIST.toArray();
	}

	@Override
	public Object getParent(Object element) {

		return null;
	}

	@Override
	public boolean hasChildren(Object element) {
		if (element != null && element instanceof Properties)
			return true;
		return false;
	}
}
